﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NUnit.Framework;
using NHibernateSample.Domain.Entities;
using NHibernate;

namespace NHibernateSample.DAL.Test
{
    [TestFixture]
    public class CRUDFixture
    {
        private NHibernateHelper _helper;
        private CRUD _crud;
        private ISession _session;
        private QueryCriteriaAPI _queryCriteriaAPI;
        private NHibernateSample _sample;
        private int newIdentity = -1;

        [TestFixtureSetUp]
        public void TestFixtureSetup()
        {
            _helper = new NHibernateHelper();
            _session = _helper.GetSession();
            HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
        }

        [SetUp]
        public void Setup()
        {
            _queryCriteriaAPI = new QueryCriteriaAPI(_session);
            _sample = new NHibernateSample(_session);
            _crud = new CRUD(_session);
        }

        [Test]
        public void CreateCustomerTest()
        {
            //新建一个Customer对象，调用CreateCustomer()方法返回新插入的CustomerId，再次根据CustomerId查询数据库是否存在这个对象。
            var customer = new Customer() { FirstName = "三", LastName = "张" };
            newIdentity = _crud.CreateCustomer(customer);
            var testCustomer = _sample.GetCustomerById(newIdentity);
            Assert.IsNotNull(testCustomer);
        }

        [Test]
        public void UpdateCustoemrTest()
        {
            newIdentity = 11;
            var customer = _sample.GetCustomerById(newIdentity);
            customer.FirstName = "永";
            _crud.UpdateCustomer(customer);
            var testCustomer = _sample.GetCustomerById(newIdentity);
            Assert.AreEqual("永", testCustomer.FirstName);
        }

        [Test]
        public void DeleteCustomerTest()
        {
            newIdentity = 20;
            var customer = _sample.GetCustomerById(newIdentity);
            _crud.DeleteCustomer(customer);
            var testCustomer = _sample.GetCustomerById(newIdentity);
            Assert.IsNull(testCustomer);
        }
       
        [Test]
        public void SaveOrUpdateCustomerTest()
        {
            IList<Customer> customers = _queryCriteriaAPI.UseCriteriaAPI_GetCustomersByFirstName("永");
            foreach (var c in customers)
            {
                c.FirstName = "董";
            }
            var c1 = new Customer() { FirstName = "三", LastName = "张" };
            var c2 = new Customer() { FirstName = "五", LastName = "王" };
            customers.Add(c1);
            customers.Add(c2);
            int initiaIListCount = customers.Count;

            _crud.SaveOrUpdateCustomer(customers);

            int testListCount = _queryCriteriaAPI.UseCriteriaAPI_GetCustomersByFirstNameAndLastName("五", "王").Count;
            Assert.AreEqual(1, testListCount);
        }
    }
}
